
package org.OpenGeoPortal.User;

import org.campusit.DatabaseTable.*;
import org.campusit.DatabaseTable.DatabaseTable.DatabaseRow;
import org.OpenGeoPortal.SiteCustomizable.UserAuthorization.Role;


/**
 * This class uses a database table to maintain a list of web site administrators.
 * It contains functions to manage the list as well as determining if a given user is an admin.
 * There is no support for fine-grained authorization, either is user is a full admin 
 *   or they are a complete non-admin.
 *   
 * @author stevemcdonald
 */
public class UserAuthorization extends DatabaseTable 
	implements org.OpenGeoPortal.SiteCustomizable.UserAuthorization 
{
	/** 
	 * the database table contains only two columns: an id and a username
	 */
	public static enum ColumnName {Username, Role};
	
	public UserAuthorization()
	{
		super("OpenGeoPortalAdmins", ColumnName.values());
	}
	

	/**
	 * provide default values
	 */
	@Override
	public void initRow(DatabaseRow row)
	{
		row.put(ColumnName.Username, "");
		row.put(ColumnName.Role, Role.User);
	}
	

	/* return true only if the user is in the list of admins
	 * @see org.OpenGeoPortal.SiteCustomizable.UserAuthorization#isAdmin(java.lang.String)
	 */
	public boolean isAdmin(String username) 
	{
		if (username == null) 
			return false;
		if (username.length() == 0)
			return false;
		DatabaseRow row = select(ColumnName.Username, username);
        if (row != null)
        	return true;
        return false;
	}
	
	public Role getRole(String username)
	{
		DatabaseRow row = select(ColumnName.Username, username);
		if (row == null)
			return Role.User;
		return (Role)row.get(ColumnName.Role);
	}
	
	/**
	 * add the passed username to the list of admins
	 * @param username
	 */
	public void addAdmin(String username)
	{
		if (isAdmin(username))
			return;
		DatabaseRow row = create();
		row.put(ColumnName.Username, username);
		row.dbSave();
	}
	
	/**
	 * delete the passed user from the list of web site admins
	 * @param username
	 */
	public void deleteAdmin(String username)
	{
		DatabaseRow row = select(ColumnName.Username, username);
		if (row == null)
			return;
		row.dbDelete();
	}
	
	

}
